﻿using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Read.Apilication.Common.Report;
using B.S.BasicData.Read.DTOS;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.BasicData.Read.Apilication.Handler.Report
{
    public class GetleavesummaryHandler : IRequestHandler<GetleavesummaryCommand, ApiResult<List<ReportDTO>>>
    {
        private readonly SCDbContext dbContext;
        private readonly IBaseRepository<UserModel> userRepo;
        private readonly IBaseRepository<leaveModel> leaveRepo;

        public GetleavesummaryHandler(SCDbContext dbContext,IBaseRepository<UserModel> userRepo,IBaseRepository<leaveModel> leaveRepo)
        {
            this.dbContext = dbContext;
            this.userRepo = userRepo;
            this.leaveRepo = leaveRepo;
        }

        public  Task<ApiResult<List<ReportDTO>>> Handle(GetleavesummaryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<ReportDTO>> res=new ApiResult<List<ReportDTO>>();
            //获取所有用户
            var users =  dbContext.UserModel.ToList();

            //初始化汇总数据
            var summarylist=new List<ReportDTO>();

            foreach (var user in users)
            {
                var summary = new ReportDTO
                {
                    UserId=user.UserId,
                    UserName=user.UserName,
                    MonthlyHours=new List<int>(new int[12])
                };

                //查询用户在指定年份的所有请假记录
                var leaveRecords = leaveRepo.GetAll().Where(x => x.UserId == user.UserId && x.leaveTime.Year == request.Year).ToList(); ;

                //统计每个月的请假工时
                foreach (var item in leaveRecords)
                {
                    int month = item.leaveTime.Month - 1;
                    summary.MonthlyHours[month] += item.Number;
                }
                summarylist.Add(summary);

                
            }
            res.Data = summarylist;
            res.Code = ApiEnum.Success;
            res.Message = "查询成功";
            return Task.FromResult(res);
        }
    }
}
